package Math;

public class _640_SolvetheEquation {
    public String solveEquation(String equation) {
        String[] equas = equation.split("=");
        int leftCoefficient = 0,rightCoefficient = 0;
        int leftConstant = 0,rightConstant = 0;
        int[] temp = getCoeffienct(equas[0]);
        leftConstant = temp[0];
        leftCoefficient = temp[1];
        temp = getCoeffienct(equas[1]);
        rightConstant = temp[0];
        rightCoefficient = temp[1];
        //apart the x and the constant
        leftCoefficient = leftCoefficient - rightCoefficient;
        rightConstant = rightConstant - leftConstant;
        System.out.println(leftCoefficient+":"+leftConstant);
        System.out.println(rightCoefficient+":"+rightConstant);
        if (leftCoefficient == 0) {
            if (rightConstant == 0) {
                return "Infinite solutions";
            } else {
                return "No solution";
            }
        } else {
            return "x=" + rightConstant / leftCoefficient;
        }
    }

    //get the constant and coefficient in the equation.
    public int[] getCoeffienct(String s) {
        int[] results = new int[2];
        String temp = "";
        boolean isCoefficient = false;
        for (char c : s.toCharArray()) {
            if (c == '+') {
                if (isCoefficient) {
                    results[1] += Integer.parseInt(temp);
                    isCoefficient = false;
                } else {
                    results[0] += Integer.parseInt(temp);
                }
                temp = "";
            } else if (c == '-') {
                if (temp.equals("")) {
                }else{
                    if (isCoefficient) {
                        results[1] += Integer.parseInt(temp);
                        isCoefficient = false;
                    } else {
                        results[0] += Integer.parseInt(temp);
                    }
                    temp = "";
                }
                temp += '-';
            } else if (c == 'x') {
                isCoefficient = true;
                if (temp.equals("") || temp.equals("-")) {
                    temp+="1";
                }
            } else {
                temp += c;
            }
        }
        //deal with the end
        if (isCoefficient) {
            results[1] += Integer.parseInt(temp);
            isCoefficient = false;
        } else {
            results[0] += Integer.parseInt(temp);
        }
        return results;
    }
}
